// 登录请求，获取菜单


export function getAccessToken() {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: "weixin",
			success: (res) => {
				if (res !== undefined) {
					let param = {
						js_code: res.code
					};
					getOpenId2(param).then(res => {
						if (res !== undefined && res.data !== undefined) {
							resolve(res.data);
						}
					})
				}
			},
			fail(e) {
				console.log("获取openid异常:", JSON.stringify(e));
				reject(e);
			}
		});
	});
}


export function getUserOpenId() {
	return new Promise((resolve, reject) => {
		const openid = uni.getStorageSync("UserOpenId");
		if (!openid  && openid !== "") {
			resolve(openid);
		} else {
			uni.login({
				provider: "weixin",
				success: (res) => {
					if (res !== undefined && res.code) {
						uniCloud.callFunction({
							name: "getOpenId",
							data: {
								code: res.code
							}
						}).then(res => {
							if (res !== undefined && res.result !== undefined) {
								uni.setStorage({
									data: res.result,
									key: "UserOpenId",
									success: () => {},
								});
								resolve(res.result);
							}
						})
					}
				},
				fail(e) {
					console.log("获取openid异常:", JSON.stringify(e));
					reject(e);
				}
			});
		}
	});
}


export function getUserIsVip() {
	return new Promise((resolve, reject) => {
		getUserInfo().then(res => {
			if(res.isAdUser){
				let nowDate = new Date().getTime();
				if (res.expireDate > nowDate) {
					resolve(2);
				} else {
					resolve(0);
				}
			}else{
				uni.getSystemInfo({
					success: (data => {
						if (data && data.osName.toLowerCase() === "ios") {
							resolve(1)
						} else {
							let nowDate = new Date().getTime();
							if (res.expireDate > nowDate) {
								resolve(2);
							} else {
								resolve(0);
							}
						}
					})
				});
			}
		}).catch(e => {
			reject(e);
		});

	});
}

export function getUserInfo() {
	return new Promise((resolve, reject) => {
		getUserOpenId().then(res => {
			wxLogin({
				openId: res,
				isNature: 1,
			}).then(userInfo => {
				resolve(userInfo.result);
			}).catch(e => {
				reject(e);
			});
		});
	});
}

export function wxLogin(param) {
	return new Promise((resolve, reject) => {
		uniCloud.callFunction({
			name: "wxLoginUser",
			data: param
		}).then(res => {
			resolve(res);
		}).catch(e => {
			reject(e);
		});
	});
}